﻿using System.Net;

namespace DataManageSystem.Exceptions
{
    public class GlobalExceptionMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger<GlobalExceptionMiddleware> _logger;

        public GlobalExceptionMiddleware(RequestDelegate next, ILogger<GlobalExceptionMiddleware> logger)
        {
            _next = next;
            _logger = logger;
        }

        public async Task InvokeAsync(HttpContext httpContext)
        {
            try
            {
                await _next(httpContext);
            }
            catch (ServiceException serviceException)
            {
                // 捕获 ServiceException 并返回自定义错误信息
                _logger.LogError(serviceException, "A service error occurred.");
                await HandleExceptionAsync(httpContext, serviceException);
            }
            catch (Exception ex)
            {
                // 捕获通用异常并返回系统错误信息
                _logger.LogError(ex, "An unexpected error occurred.");
                await HandleExceptionAsync(httpContext, ex);
            }
        }

        private Task HandleExceptionAsync(HttpContext context, Exception exception)
        {
            var statusCode = exception is ServiceException ? HttpStatusCode.BadRequest : HttpStatusCode.InternalServerError;
            var message = exception.Message;
            var code = exception is ServiceException serviceEx ? serviceEx.Code : "500";

            context.Response.ContentType = "application/json";
            context.Response.StatusCode = (int)statusCode;

            var result = new
            {
                Message = message,
                Code = code,
                Timestamp = DateTime.Now
            };

            return context.Response.WriteAsJsonAsync(result);
        }
    }
}
